package com.huiyun.project.im.api.biz.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huiyun.project.base.controller.BaseController;
import com.huiyun.project.common.core.domain.R;
import com.huiyun.project.common.core.domain.Table;
import com.huiyun.project.common.core.util.fn.FunctionUtils;
import com.huiyun.project.im.api.client.vo.req.tenant.ImTenantsReq;
import com.huiyun.project.im.api.client.vo.req.user.ImUserReq;
import com.huiyun.project.im.common.auth.SecurityUtils;
import com.huiyun.project.im.common.auth.UserPrincipal;
import com.huiyun.project.im.consts.ImServerConst;
import com.huiyun.project.im.consts.ImUserConst;
import com.huiyun.project.im.core.dto.ImUserDto;
import com.huiyun.project.im.core.service.IImCsSessionService;
import com.huiyun.project.im.core.service.IImUserService;
import com.huiyun.project.im.entity.ImCsSession;
import com.huiyun.project.im.entity.ImUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Logical;
import org.wf.jwtp.annotation.RequiresRoles;

import java.util.Date;
import java.util.List;

/**
 * @FileName:ApiImSpController
 * @Description: 提供给服务商的接口
 * @Author linjie
 * @Date 2020/7/1711:19 AM
 * @Version 4.0.0
 */
@RestController
@RequestMapping("im/api/tenant/{version}")
@AllArgsConstructor
@Api(tags = "企业租户集成")
public class ApiImTenantController extends BaseController {

    private final IImUserService userService;

    private final IImCsSessionService sessionService;


    @GetMapping("/subs/{tenantId}")
    @ApiOperation("根据租户查询子账号列表")
    @RequiresRoles({ImServerConst.API_SP_ROLE})
    public R subs(@PathVariable String tenantId) {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });
    }

    @GetMapping("/subs")
    @ApiOperation("查询登陆租户子账号列表")
    @RequiresRoles({ImServerConst.API_SP_ROLE})
    public R subs() {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });
    }

    /**
     * 租户修改客服账号
     *
     * @param imUser
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("修改子账号")
    @RequiresRoles(value = {ImServerConst.API_TENANT_ROLE, ImServerConst.API_USER_ROLE}, logical = Logical.OR)
    public R edit(@RequestBody ImUser imUser) {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });
    }





    /**
     * 租户聊天记录查询
     *
     * @return
     */
    @GetMapping("/chat/msg")
    @ApiOperation("聊天记录查询")
    @RequiresRoles({ImServerConst.API_TENANT_ROLE})
    public R chatMsg() {
        return FunctionUtils.wrapper(() -> {
            //限制只能查当前租户
            return R.ok();
        });
    }


    @PostMapping("/report/chat")
    @ApiOperation("消息统计")
    @RequiresRoles({ImServerConst.API_TENANT_ROLE})
    public R reportChat() {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });
    }


    @PostMapping("/orgs")
    @ApiOperation("创建或者修改IM客服组")
    @RequiresRoles({ImServerConst.API_TENANT_ROLE})
    public R orgs(@RequestBody Object obj) {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });
    }


    @GetMapping("/orgs")
    @ApiOperation("查询IM客服组")
    @RequiresRoles({ImServerConst.API_TENANT_ROLE})
    public R orgs(Long pageNum, Long pageSize, String name) {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });
    }


    @DeleteMapping("/orgs/{orgId}")
    @ApiOperation("删除客服组")
    @RequiresRoles({ImServerConst.API_TENANT_ROLE})
    public R orgs(@PathVariable String orgId) {
        return FunctionUtils.wrapper(() -> {
            //系统内置不可删除
            return R.ok();
        });
    }

    @PostMapping("/upgrade")
    @ApiOperation("个人账号升级企业租户")
    @RequiresRoles({ImServerConst.API_USER_ROLE})
    public R upgrade(@RequestBody List<ImTenantsReq> tenantCreateReq) {
        return FunctionUtils.wrapper(() -> {
            return R.ok();
        });

    }


    /***
     * 租户删除员工
     * @return
     */
    @DeleteMapping("/delUser/{userId}")
    @ApiOperation("租户删除员工")
    public R del(@PathVariable("userId") String userId) {
        return FunctionUtils.wrapper(() -> {
            UserPrincipal userPrincipal = SecurityUtils.getUserPrincipal();
            ImUser imUser = userService.getById(userId);
            Assert.notNull(imUser);
            if (!imUser.getImTenantId().equals(userPrincipal.getImTenantId())) {
                return R.failed("对不起，无权限操作");
            }
            imUser.setModifyTime(new Date());
            imUser.setModifyBy(userPrincipal.getId());
            imUser.setDelFlag(ImServerConst.DEL_FLAG_1);
            return R.ok(userService.updateById(imUser));
        });

    }


    @GetMapping("/{username}/blacklist")
    @ApiOperation("获取一个IM用户的黑名单。黑名单中的用户无法给该 IM 用户发送消息。")
    public R<String> blacklist(List<ImUserReq> imUserReqList) {
        return R.ok();
    }


    /**
     * 子账户授权客服
     *
     * @param imUserDto
     * @return
     */
    @PostMapping("grantUser")
    @RequiresRoles(value = {ImServerConst.API_USER_ROLE, ImServerConst.API_TENANT_ROLE}, logical = Logical.OR)
    public R grantUser(@RequestBody ImUserDto imUserDto) {
        return FunctionUtils.wrapper(() -> {
            UserPrincipal userPrincipal = SecurityUtils.getUserPrincipal();
            Assert.notBlank(imUserDto.getId());
            ImUser imUser = userService.getById(imUserDto.getId());
            Assert.notNull(imUser);
            if (!imUser.getImTenantId().equals(userPrincipal.getImTenantId())) {
                return R.failed("对不起，无权限操作");
            }
            imUser.setType(ImUserConst.TYPE_2);
            imUser.setModifyTime(new Date());
            imUser.setModifyBy(userPrincipal.getId());
            return R.ok(userService.updateById(imUser));
        });
    }

    /**
     * 子账户授权客服
     *
     * @param imUserDto
     * @return
     */
    @PostMapping("revokeUser")
    @RequiresRoles(value = {ImServerConst.API_USER_ROLE, ImServerConst.API_TENANT_ROLE}, logical = Logical.OR)
    public R revokeUser(@RequestBody ImUserDto imUserDto) {
        return FunctionUtils.wrapper(() -> {
            UserPrincipal userPrincipal = SecurityUtils.getUserPrincipal();
            Assert.notBlank(imUserDto.getId());
            ImUser imUser = userService.getById(imUserDto.getId());
            Assert.notNull(imUser);
            if (!imUser.getImTenantId().equals(userPrincipal.getImTenantId())) {
                return R.failed("对不起，无权限操作");
            }
            imUser.setType(ImUserConst.TYPE_1);
            imUser.setModifyTime(new Date());
            imUser.setModifyBy(userPrincipal.getId());
            return R.ok(userService.updateById(imUser));
        });
    }

    @GetMapping("/session/history")
    @ApiOperation("分页获取历史会话")
    @RequiresRoles(value = {ImServerConst.API_USER_ROLE, ImServerConst.API_TENANT_ROLE}, logical = Logical.OR)
    public Table historySession(@RequestParam(name = "username", required = false) String userName,
                                @RequestParam(name = "csName", required = false) String csName,
                                @RequestParam(name = "startTime", required = false) Date startTime,
                                @RequestParam(name = "endTime", required = false) Date endTime,
                                @RequestParam(name = "serviceStartTime", required = false) Date serviceStartTime,
                                @RequestParam(name = "serviceEndTime", required = false) Date serviceEndTime,
                                @RequestParam(name = "userSource", required = false) Integer userSource
    ) {
        return FunctionUtils.wrapper1(() -> {
            return convert(sessionService.page(buildPage(), Wrappers.<ImCsSession>lambdaQuery()
                    .eq(ImCsSession::getCsTenantId, SecurityUtils.getUserPrincipal().getImTenantId())
                    .orderByDesc(ImCsSession::getBeginTime)
                    .like(StringUtils.isNotBlank(userName), ImCsSession::getUserNick, userName)
                    .like(StringUtils.isNotBlank(csName), ImCsSession::getCsNick, csName)
                    .ge(null != startTime, ImCsSession::getBeginTime, startTime)
                    .le(null != endTime, ImCsSession::getBeginTime, endTime)
                    .ge(null != serviceStartTime, ImCsSession::getCsFirstTime, serviceStartTime)
                    .le(null != serviceEndTime, ImCsSession::getCsFirstTime, serviceEndTime)
                    .le(null != userSource, ImCsSession::getUserSource, userSource)
            ));
        });
    }
}
